//
//  HomeViewController.m
//  EducationOID
//
//  Created by slz on 2017/5/17.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "HomeViewController.h"
#import <LBXScanView.h>
#import "OIScanViewController.h"
#import "MoreViewController.h"

#import "HomeNewsModel.h"
#import "HomeNewsItem.h"

#import "OIPubListViewController.h"
#import "OIWorkInfoListViewController.h"
#import "OIQRScanResultViewController.h"
#import "OIWorkInfoDetailViewController.h"

#import "OIDInfoRequestModel.h"

#import "NSString+OIDAnalysis.h"
#import "NSURL+QueryDict.h"
#import "NewWebViewController.h"
#import "CircleViewController.h"
#import "OIDCacheManager.h"
#import "OIDSystemSettingManager.h"
#import "BaseHttpTool.h"

@interface HomeViewController ()<MFWDataObserver>
@property (weak, nonatomic) IBOutlet UIButton *analysisButton;
@property (weak, nonatomic) IBOutlet UITextField *analysisTextField;
@property (weak, nonatomic) IBOutlet UILabel *newsLabel1;
@property (weak, nonatomic) IBOutlet UILabel *newsLabel2;
@property (weak, nonatomic) IBOutlet UILabel *newsLabel3;

@end

@implementation HomeViewController
{
    HomeNewsModel * _model;
    OIDInfoRequestModel * _oidModel;
    NSArray * _labelArray;
    NSMutableArray * _itemArray;
    BOOL _jumpWeb;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.newsLabel1 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTap:)]];
    [self.newsLabel2 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTap:)]];
    [self.newsLabel3 addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTap:)]];
    self.newsLabel1.tag = 1;
    self.newsLabel2.tag = 2;
    self.newsLabel3.tag = 3;
    _labelArray = @[_newsLabel1,_newsLabel2,_newsLabel3];
    _itemArray = @[].mutableCopy;
    self.showNavigationBar = YES;
    self.view.backgroundColor = kBack_Color_Default;
    UIBarButtonItem * leftItem = [UIBarButtonItem itemWithImage:@"icon_scan" selectImage:nil addTarget:self andAction:@selector(scanAction)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIBarButtonItem * rightItem = [UIBarButtonItem itemWIthTitle:@"更多" addTarget:self andAction:@selector(moreAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UIImageView * leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.contentMode = UIViewContentModeCenter;
    leftImageView.image = [UIImage imageNamed:@"search_icon_1"];
    
    [_analysisButton setTitleColor:kDark_TextColor_Default forState:UIControlStateNormal];
    _analysisButton.layer.cornerRadius = 5;
    _analysisButton.titleLabel.fontSize = 15;
    _analysisTextField.placeholder = @"请输入OID";
    _analysisTextField.leftViewMode = UITextFieldViewModeAlways;
    _analysisTextField.leftView = leftImageView;
    [self requestDetailInfo];
    // Do any additional setup after loading the view from its nib.
}

-(void)requestDetailInfo {
    if(_model == nil) {
        _model = [HomeNewsModel managedModelInstance];
        [[_model class] addDataObserver:self];
    }
    [_model requestRefresh:[_model actionData]];
}

-(void)requestFinishedForTask:(MFWTask *)task withModel:(MFWDataModel *)model dataId:(NSString *)dataId requestType:(MFWDataRequestType)type itemArray:(NSArray *)itemArray success:(BOOL)bSuccess error:(NSError *)error{
    if (model == _model && bSuccess){
        MFWJson * json =  [_model jsonDataForDataId:dataId];
        if (json.count > 0){
            [self updateNewsWithJson:json];
        }
    }
   
    if (model == _oidModel){
        if (bSuccess && error == nil){
            MFWJson * json = [model jsonDataForDataId:dataId];
            BOOL isOid = [json booleanValueForKey:@"parameter"];
            if (!isOid){
                NSString * errorInfo = [json stringValueForKey:@"data"];
                [self.view showTip:errorInfo];
                if (_jumpWeb){
                    _jumpWeb = NO;
                    NSString * urlString = _analysisTextField.text;
                    BOOL isUrl = [urlString isUrl];
                    if (isUrl){
                        [self jumpWebControllerWithUrl:urlString];
                    }
                }
            }else{
                NSString * successsString = [json stringValueForKey:@"data"];
                OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
                resultController.resultSuccessUrl = successsString;
                resultController.isQrcode = NO;
                resultController.isOidValid = YES;
                resultController.canJump = YES;
                [self.navigationController pushViewController:resultController animated:YES];
            }
        }else{
            [self.view showTip:@"请求错误~"];
        }
    }
}

- (void)updateNewsWithJson:(MFWJson *)json{
    for (int i = 0; i < json.count; i++){
        if (i>=3) break;
        HomeNewsItem * item = [[HomeNewsItem alloc]initWithJson:[json jsonAtIndex:i]];
        [_itemArray addObject:item];
        UILabel * newLabel = _labelArray[i];
        newLabel.text = item.title;
    }
}

- (void)scanAction{
    OIScanViewController * scanViewController = [[OIScanViewController alloc]init];
    scanViewController.style = [self wechatStyle];
    scanViewController.isOpenInterestRect = YES;
    scanViewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:scanViewController animated:YES];
}

- (void)moreAction{
    MoreViewController * moreController = [[MoreViewController alloc]init];
    [self.navigationController pushViewController:moreController animated:YES];
}

-(LBXScanViewStyle *)wechatStyle{
    //设置扫码区域参数
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    
    style.centerUpOffset = 44;
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Inner;
    style.photoframeLineW = 2;
    style.photoframeAngleW = 18;
    style.photoframeAngleH = 18;
    style.isNeedShowRetangle = YES;
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    style.colorAngle = [UIColor colorWithRed:0./255 green:200./255. blue:20./255. alpha:1.0];
    
    //qq里面的线条图片
    UIImage *imgLine = [UIImage imageNamed:@"qrcode_Scan_weixin_Line"];
    style.animationImage = imgLine;
    
    return style;
}
- (IBAction)requestBaseInfo:(id)sender {
    [_analysisTextField resignFirstResponder];
    NSString * urlString = _analysisTextField.text;
    if (urlString.length == 0){
        [self.view showTip:@"请输入OID信息"];
        return;
    }
    BOOL isUrl = [urlString isUrl];

    OIDCacheManager * manager = [OIDCacheManager shareInstance];
    [manager uopdateWithAnalysisOidString:urlString];
    
    if (isUrl){
        if ([urlString isContainOidCenter]){
            NSURL * url = [NSURL URLWithString:urlString];
            NSString * oidString = [url queryValueWithKey:@"oid"];
            _jumpWeb = YES;
            [self requestWithOidString:oidString];
        }else
        {
            [self requestWithOidType1:urlString];
        }
    }else{
        if ([urlString isContainOID]){
            urlString = [urlString substringFromIndex:4];
            [self requestWithOidType2:urlString];
        }else
        {
            [self requestWithOidString:urlString];
        }
        //todo 不是url 直接请求
    }
}

- (void)requestWithOidType2:(NSString *)oidString
{
    [BaseHttpTool get:kAPI_OID_SEARCH_OID_NEW params:@{@"type":@"2",@"url":oidString} success:^(id responseObj) {
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        BOOL isOID = [json booleanValueForKey:@"parameter"];
        if (!isOID){
            [self.view showTip:@"请求错误"];
        }else
        {
            MFWJson * subJson = [json jsonForKey:@"rows"];
            NSString * successsString = [subJson stringValueForKey:@"url"];
            OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
            resultController.resultSuccessUrl = successsString;
            resultController.isQrcode = NO;
            resultController.isOidValid = YES;
            resultController.canJump = NO;
            [self.navigationController pushViewController:resultController animated:YES];
        }
        
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}

- (void)requestWithOidType1:(NSString *)oidString
{
    NSString * scanString = oidString;
    NSURL * url = [NSURL URLWithString:oidString];
    if (![url.host isEqualToString:@"weixin.qq.com"]){
        oidString = [NSString stringWithFormat:@"%@://%@",url.scheme,url.host];
        NSLog(@"%@",oidString);
    }
    [BaseHttpTool get:kAPI_OID_SEARCH_OID_NEW params:@{@"type":@"1",@"url":oidString} success:^(id responseObj) {
        
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        BOOL isOID = [json booleanValueForKey:@"parameter"];
        MFWJson * subJson = [json jsonForKey:@"rows"];
        //            NSString * successsString = [subJson stringValueForKey:@"url"];
        OIQRScanResultViewController * resultController = [[OIQRScanResultViewController alloc]init];
        resultController.resultSuccessUrl = scanString;
        resultController.isQrcode = NO;
        resultController.isOidValid = isOID;
        resultController.canJump = YES;
        NSInteger oidType = [subJson intValueForKey:@"oid_type"];
        resultController.canJump = oidType == 2 ? NO :YES;
        resultController.resultName = [subJson stringValueForKey:@"name"];
        resultController.typeCount = [subJson intValueForKey:@"oid_type"];
        [self.navigationController pushViewController:resultController animated:YES];
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];
}

- (void)jumpWebControllerWithUrl:(NSString *)url{
    NewWebViewController * webController = [[NewWebViewController alloc]init];
    webController.url = url;
    [self.navigationController pushViewController:webController animated:YES];
}

- (void)requestWithOidString:(NSString *)oidString{
    if(_oidModel == nil) {
        _oidModel = [OIDInfoRequestModel managedModelInstance];
        [[_oidModel class] addDataObserver:self];
    }
    [_oidModel requestRefresh:[_oidModel actionDataWithOIDString:oidString]];
}


- (IBAction)pubInfoAction:(id)sender {
    OIPubListViewController * listController = [[OIPubListViewController alloc]init];
    listController.isPub = YES;
    [self.navigationController pushViewController:listController animated:YES];
}

- (IBAction)pubInfoShowAction:(id)sender {
    OIPubListViewController * listController = [[OIPubListViewController alloc]init];
    listController.isPub = NO;
    [self.navigationController pushViewController:listController animated:YES];
//    CircleViewController * cllllllll = [[CircleViewController alloc]init];
//    [self.navigationController pushViewController:cllllllll animated:YES];
}

- (IBAction)moreNewsAction:(id)sender {
    OIWorkInfoListViewController * workController = [[OIWorkInfoListViewController alloc]init];
    workController.type = NO;
    [self.navigationController pushViewController:workController animated:YES];
}

- (IBAction)workInfoAction:(id)sender {
    OIWorkInfoListViewController * workController = [[OIWorkInfoListViewController alloc]init];
    workController.type = YES;
    [self.navigationController pushViewController:workController animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)labelTap:(UITapGestureRecognizer *)tap{
    HomeNewsItem * item;
    if (tap.view.tag ==1){
        item = _itemArray[0];
    }else if (tap.view.tag == 2){
        item = _itemArray[1];
    }else{
        item = _itemArray[2];
    }
    OIWorkInfoDetailViewController * detailController = [[OIWorkInfoDetailViewController alloc]init];
    detailController.itemId = item.newsId;
    [self.navigationController pushViewController:detailController animated:YES];
}

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    //shake jump to scan QR code controller
    if ([OIDSystemSettingManager shareManager].shakeToCamera){
        OIScanViewController * scanViewController = [[OIScanViewController alloc]init];
        scanViewController.style = [self wechatStyle];
        scanViewController.isOpenInterestRect = YES;
        scanViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:scanViewController animated:YES];        
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
